<template>
  <div id="upload">
    <el-upload 
    @click="handleRemove"
    class="avatar-uploader"
    :show-file-list="false"
    ref="upload"
    list-type="picture-card"
    action="/api/upload/uploadImg" 
    name="img"
    :before-upload="handleBeforeUpload"
    :on-success="handleSuccess"
    :limit="1"
    >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

  
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  </div>
</template>
<script setup>
import { ref ,reactive,watchEffect} from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage} from 'element-plus'

// import { UploadFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file) => {
  // console.log(file)
  upload.value.handleRemove(file)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {
  console.log(file)
}
let props =defineProps([
  "modelValue"
])
let imageUrl = ref('')
watchEffect(()=>{
  
    imageUrl.value = props.modelValue
  
  },{
    flush: 'post'
  })

let handleBeforeUpload = (rawFile)=>{
  //  console.log("rawFile",rawFile);
   let rawType = ['image/webp', 'image/png', 'image/jpeg', 'image/gif']
    if (!rawType.includes(rawFile.type)) {
        ElMessage.error('上传的文件类型必须是:' + rawType.join(',') + '中的一种')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('文件上传大小不能超过1MB!')
        return false
    }
    return true
}
let emit = defineEmits(['update:modelValue'])
//上传成功

const handleSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
    // console.log(response)
    if(response.state){
        emit('update:modelValue', response.imgUrl)
    } else {
        ElMessage.error('上传出错')
    }
}


let upload = ref()
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

